<template>
    <div>
        <div class="header">单聊模式</div>

        <div>
            <kv label="我的用户Id">
                {{userId}}
            </kv>
            <kv label="我的用户名">
                {{userName}}
            </kv>

            <div :class="{'user':1, 'selected' : talkUserId==1 }" data-id="1" @click="chat($event)">
                user1
            </div>
            <div :class="{'user':1, 'selected' : talkUserId==2 }" data-id="2" @click="chat($event)">
                user2
            </div>
            <div :class="{'user':1, 'selected' : talkUserId==3 }" data-id="3" @click="chat($event)">
                user3
            </div>
        </div>
        <div style="margin:10px;">
            <kv label="消息">
                <textarea v-model="msg"></textarea>
            </kv>
            <button @click="send">发送</button>
        </div>
        <ul style="margin:10px">
            <li v-for="(item,index) in list" :key="index">
                <span>{{item.userId}}:</span>{{item.content}}
            </li>
        </ul>
    </div>
</template>
<style scoped>
    >>> .user {
        width: 100px;
        height: 100px;
        border: solid 1px green;
        background: #1ebcc5;
        display: inline-block;
        margin: 5px;
    }

    >>> .user.selected {
        border: solid 1px #2f3080;
        background: #c5c434;
    }

</style>
<script>
    import io from "socket.io-client"

    export default {
        data() {
            return {socket: null, talkUserId: "", list: [], msg: "", userId: "abc",userName:""}
        },
        mounted() {
            this.userId = location.hashJson.userId;
            this.userName = location.hashJson.userName;
        },
        methods: {
            init() {
                if (this.socket) {
                    this.socket.close();
                }
                this.socket = io.connect("ws://localhost:3000");


                //接受消息
                this.socket.on('message', data => {
                    this.list.push(data);
                });

                // this.socket.on("chat", data => {
                //     this.room = data;
                // });
            },
            chat(ev) {
                this.init();

                var id = ev.target.dataset.id;
                this.talkUserId = id;


                // this.socket.emit('chat', {master: id, user: this.userId});
            },
            send() {
                this.socket.emit("talk", "", this.userId,this.talkUserId,  this.msg);
                this.msg = "";
            }
        }
    }
</script>
